import * as React from 'react'
import DatePicker from 'react-mobile-datepicker'
import { Toast } from 'antd-mobile'
import Cropper from 'react-cropper'
import 'cropperjs/dist/cropper.css'
import { Gird, NavBar, Button } from 'components'
import LightBox from './LightBox'
import { hash } from 'muka'
import moment from 'moment'
import './index.less'
import { post } from '../../../utils'

const ImageTypes: string[] = ['image/jpeg', 'image/jpg', 'image/png']

export default class Info extends React.Component<any, any> {

    public state = {
        showTime: false,
        time: new Date(),
        selectPhotoArr: [],
        previewImg: [],
        visible2: false,
        visible1: false,
        aspect: 1 / 1,
        showCopper: false
    }
    public inputRef: any
    private cropper: any
    private cropperData: any
    public render(): JSX.Element {
        const { userInfo } = this.props
        const { showTime, time, visible2, visible1, aspect, previewImg, showCopper } = this.state
        return (
            <div className="account">
                <NavBar title="个人信息" />
                <Gird style={{ marginTop: 0 }}>
                    <Gird.Item 
                        title="头像" 
                        link={true} 
                        value={
                            (userInfo.ico) 
                            ? <div className="account_uploadImg" onClick={() => {this.setState({visible1: true})}}>
                                <LightBox 
                                    imgClass="account_uploadImg_lightBoxImg"
                                    onClose={() => {this.handleClose('visible1')}} 
                                    src={userInfo.ico} 
                                    visible={visible1}
                                    renderBotom={<div className="account_uploadImg_btnWrap">
                                        <input type="file" className="account_uploadImg_btn show" accept="image/*" ref={(ref) => { this.inputRef = ref }} onChange={this.handleSelectPhoto} />
                                        <Button className="account_uploadImg_btn">更换头像</Button>
                                    </div>}
                                >
                                    <img className="user_logo" src={userInfo.ico} />
                                </LightBox>
                            </div>
                            : <div className="account_uploadImg" onClick={() => {this.setState({visible2: true})}} >
                                <LightBox 
                                    imgClass="account_uploadImg_lightBoxImg"
                                    renderBotom={<div className="account_uploadImg_btnWrap">
                                        <input type="file" className="account_uploadImg_btn show" accept="image/*" ref={(ref) => { this.inputRef = ref }} onChange={this.handleSelectPhoto} />
                                        <Button className="account_uploadImg_btn">上传头像</Button>                                        
                                    </div>}
                                    onClose={() => {this.handleClose('visible2')}} 
                                    src={require('../../../assets/personCenter_defaultImg.png')} 
                                    visible={visible2}
                                >
                                    <img className="user_logo" src={require('../../../assets/personCenter_defaultImg.png')} />
                                </LightBox>
                            </div>
                        }
                    />
                    <Gird.Item title="昵称" value={userInfo.nick_name} link="/My/reName" />
                    <Gird.Item title="生日" onPress={() => {this.handleShowTime('showTime')}} value={<span>{userInfo && userInfo.birthday}</span>} link={true} />
                    <Gird.Item title="收货地址" value="修改/添加" link="/My/address/1" />
                </Gird>
                <DatePicker theme="ios" value={time} max={new Date()} isOpen={showTime} onSelect={(e: any) => {this.handleSelectTime(e)}} onCancel={() => {this.handleHideTime('showTime')}} />
                {
                    showCopper && 
                        <div className="account_cropWrap">
                            <Cropper
                                ref={(ref: any) => {this.cropper = ref}}
                                src={previewImg}
                                style={{height: 400, width: '100%'}}
                                aspectRatio={aspect}
                                guides={false}
                                crop={this.handleCrop}
                            />
                            <div className="account_cropWrap_operation">
                                <div>
                                    <Button className="account_cropWrap_operation_btn" onClick={this.handleCancleCrop}>取消</Button>
                                    <Button className="account_cropWrap_operation_btn" onClick={this.handleSubmitCrop}>确定</Button>
                                </div>
                            </div>
                        </div>
                }
            </div>
        )
    }
    private handleCancleCrop = () => {
        this.setState({
            showCopper: false,
        })
        this.cropperData = ''
    }
    private handleSelectPhoto = () => {
        const arr: any = []
        const that = this
        const imgFile = this.inputRef.files[0]
        const reader = new FileReader()
        if (!imgFile) {
            return
        }
        if (!hash(ImageTypes, imgFile.type)) {
            Toast.info('只能上传图片文件哦')
            return
        }
        if ((imgFile.size / 1048576) > 4) {
            Toast.info('图片不能大于4M，请重新选择！', 2)
            return
        }
        reader.readAsDataURL(imgFile)
        reader.onload = function (e: any) {
            arr.push(this.result)
            that.setState({previewImg: arr, showCopper: true})
        }
    }
    private handleSubmitCrop = () => {
        Toast.loading('获取文件中...')
        let temp = []
        this.cropperData = this.cropper.getCroppedCanvas().toDataURL()
        temp.push(this.cropperData)
        this.setState({selectPhotoArr: temp}, this.handleUploadImg)
    }
    private handleCrop = () => {
        return
    }

    private handleUploadImg = () => {
        const { userInfo, SET_USER_INFO } = this.props
        post('indexapi/imgUpload', {
            typeImg: 'refundImg', // 图片分类
            file: this.state.selectPhotoArr // 图片文件
        }).then((data: any) => {
            Toast.loading('上传中...', 0)
            if (data.length > 0) {
                post('usersapi/userIco', {
                    userId: userInfo.id,
                    ico: data[0]
                }).then((result: any) => {
                    Toast.hide()
                    const obj = Object.assign({}, this.props.userInfo)
                    obj.ico = data[0]
                    SET_USER_INFO(obj)
                    Toast.success('图片上传成功！', 2, this.handleCancleCrop)
                }).catch(() => {
                    Toast.fail('图片上传失败！')
                    Toast.hide()
                })
            }
        }).catch(() => {
            Toast.fail('图片上传失败！')
            Toast.hide()
        })
    }
    private handleSelectTime (val: any) {
        const { userInfo, SET_USER_INFO } = this.props
        const birthday = moment(val).format('YYYY-MM-DD')
        post('usersapi/userBirthday', {
            userId: userInfo.id,
            birthday: birthday
        }).then((data: any) => {
            let obj = Object.assign({}, userInfo)
            obj.birthday = birthday
            SET_USER_INFO(obj)
        }).catch(() => {
            Toast.info('网络错误！请稍后再试！')
        })
        this.setState({
            time: val,
            showTime: false
        })
    }
    private handleShowTime = (key: string) => {
        this.setState({
            [key]: true
        })
    }
    private handleHideTime = (key: string) => {
        this.setState({
            [key]: false
        })
    }
    private handleClose = (key: string) => {
        this.setState({
            [key]: false
        })
    }
}